<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <h1>table</h1>
    <hr>

    <table width="800" border="1" cellspacing="0" cellpadding="5" id="tab">
        <tr>
            <th>序号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>班期</th>
            <th>操作</th>
        </tr>
        
        <tr>
            <td>1</td>
            <td>静静</td>
            <td>18</td>
            <td>s94</td>
            <td>
                <button onclick="deleteData(this)">删除</button>
            </td>
        </tr>

        <tr>
            <td>2</td>
            <td>彤彤</td>
            <td>188</td>
            <td>s999</td>
            <td>
                <button onclick="deleteData(this)">删除</button>
            </td>
        </tr>

        <tr>
            <td>3</td>
            <td>沙和尚</td>
            <td>800</td>
            <td>s9</td>
            <td>
                <button onclick="deleteData(this)">删除</button>
            </td>
        </tr>

        <tr>
            <td>4</td>
            <td>悟空</td>
            <td>3000</td>
            <td>666</td>
            <td>
                <button onclick="deleteData(this)">删除</button>
            </td>
        </tr>

        <tr>
            <td>5</td>
            <td>卡卡</td>
            <td>28</td>
            <td>s4</td>
            <td>
                <button onclick="deleteData(this)">删除</button>
            </td>
        </tr>
    </table>

    <br>
    <hr>
    <br>
    <br>
    <br>
    
    <form action="1.php" name="myform" onsubmit="return addData()">
        姓名: <input type="text" name="name"><br>
        年龄: <input type="text" name="age"><br>
        班期: <input type="text" name="grade"><br>

        <button type="submit">添加</button>
    </form>


    <script>
        function addData(){
            // 获取表单数据
            var name = document.myform.name.value;
            var age = document.myform.age.value;
            var grade = document.myform.grade.value;
            // console.log(name, age, grade);
            
            var table = document.getElementById('tab');

            // 获取当前表格的行数
            var index = table.rows.length;
            // console.log(index);

            var tr = table.insertRow(index);
            // console.log(tr);

            // 添加单元格信息
            tr.insertCell(0).innerHTML = index;
            tr.insertCell(1).innerHTML = name;
            tr.insertCell(2).innerHTML = age;
            tr.insertCell(3).innerHTML = grade;
            tr.insertCell(4).innerHTML = '<button onclick="deleteData(this)">删除</button>';
            return false;
        }

        //删除数据行
        function deleteData(obj) {
            //获取table
            
            var table = document.getElementById('tab');

            table.deleteRow(obj.parentNode.parentNode.rowIndex);
        }



    </script>
</body>
</html>